<?php

namespace App\Http\Controllers\Admin;

use App\Events\permChangeEvent;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\PermissionCreateRequest;
use App\Http\Requests\Admin\PermissionUpdateRequest;
use App\Models\Admin\Menu;
use App\Models\Admin\Permission;
use Event;
use Illuminate\Http\Request;

class PermissionController extends Controller
{
    protected $fields = [
        'name'        => '',
        'label'       => '',
        'description' => '',
        'icon'        => '',
        'f_pid'       => '',
    ];

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, $f_pid = 0)
    {
        $f_pid = (int) $f_pid;
        if ($request->ajax()) {
            $data         = array();
            $data['draw'] = $request->get('draw');
            $start        = $request->get('start');
            $length       = $request->get('length');
            $order        = $request->get('order');
            $columns      = $request->get('columns');
            $search       = $request->get('search');
            $f_pid        = $request->get('f_pid', 0);
            if ($f_pid > 0) {
                $data['recordsTotal'] = Permission::where('f_pid', $f_pid)->count();
                if (strlen($search['value']) > 0) {
                    $data['recordsFiltered'] = Permission::where('f_pid', $f_pid)->where(function ($query) use ($search) {
                        $query
                            ->where('name', 'LIKE', '%' . $search['value'] . '%')
                            ->orWhere('description', 'like', '%' . $search['value'] . '%')
                            ->orWhere('label', 'like', '%' . $search['value'] . '%');
                    })->count();
                    $data['data'] = Permission::where('f_pid', $f_pid)->where(function ($query) use ($search) {
                        $query->where('name', 'LIKE', '%' . $search['value'] . '%')
                            ->orWhere('description', 'like', '%' . $search['value'] . '%')
                            ->orWhere('label', 'like', '%' . $search['value'] . '%');
                    })
                        ->skip($start)->take($length)
                        ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                        ->get();
                } else {
                    $data['recordsFiltered'] = Permission::where('f_pid', $f_pid)->count();
                    $data['data']            = Permission::where('f_pid', $f_pid)->
                        skip($start)->take($length)
                        ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                        ->get();
                }
            } else {
                $data['recordsTotal'] = Permission::count();
                if (strlen($search['value']) > 0) {
                    $data['recordsFiltered'] = Permission::where(function ($query) use ($search) {
                        $query
                            ->where('name', 'LIKE', '%' . $search['value'] . '%')
                            ->orWhere('description', 'like', '%' . $search['value'] . '%')
                            ->orWhere('label', 'like', '%' . $search['value'] . '%');
                    })->count();
                    $data['data'] = Permission::where(function ($query) use ($search) {
                        $query->where('name', 'LIKE', '%' . $search['value'] . '%')
                            ->orWhere('description', 'like', '%' . $search['value'] . '%')
                            ->orWhere('label', 'like', '%' . $search['value'] . '%');
                    })
                        ->skip($start)->take($length)
                        ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                        ->get();
                } else {
                    $data['recordsFiltered'] = Permission::count();
                    $data['data']            = Permission::
                        skip($start)->take($length)
                        ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                        ->get();
                }
            }
            return response()->json($data);
        }
        $datas['f_pid']          = $f_pid;
        $datas['second_menu_id'] = '';

        if (Menu::find($f_pid)) {
            $second_menu             = Menu::find($f_pid);
            $datas['second_menu_id'] = $second_menu->f_pid; //->pluck('f_pid');
        }

        if ($f_pid > 0) {
            $datas['data'] = Permission::find($f_pid);
        }
        return view('admin.permission.index', $datas);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($f_pid)
    {
        $data = [];
        foreach ($this->fields as $field => $default) {
            $data[$field] = old($field, $default);
        }
        $data['f_pid'] = $f_pid;

        return view('admin.permission.create', $data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param PremissionCreateRequest|Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(PermissionCreateRequest $request)
    {
        $permission = new Permission();
        foreach (array_keys($this->fields) as $field) {
            $permission->$field = $request->get($field, $this->fields[$field]);
        }
        $permission->save();
        Event::fire(new permChangeEvent());

        //触发事件
        event(new \App\Events\userActionEvent('\App\Models\Admin\Permission', $permission->id, 1, '添加了权限:' . $permission->name . '(' . $permission->label . ')'));

        return redirect('/admin/permission/' . $permission->f_pid)->withSuccess('添加成功！');
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $permission = Permission::find($id);
        if (!$permission) {
            return redirect('/admin/menu')->withErrors("找不到该权限!");
        }

        $data = ['id' => (int) $id];
        foreach (array_keys($this->fields) as $field) {
            $data[$field] = old($field, $permission->$field);
        }

        return view('admin.permission.edit', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param PermissionUpdateRequest|Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(PermissionUpdateRequest $request, $id)
    {
        $permission = Permission::find($id);
        if (!$permission) {
            return redirect('/admin/menu')->withErrors("找不到该权限!");
        }
        foreach (array_keys($this->fields) as $field) {
            $permission->$field = $request->get($field, $this->fields[$field]);
        }
        $permission->save();

        //触发事件
        Event::fire(new permChangeEvent());
        event(new \App\Events\userActionEvent('\App\Models\Admin\Permission', $permission->id, 3, '修改了权限:' . $permission->name . '(' . $permission->label . ')'));

        return redirect('admin/permission/' . $permission->f_pid)->withSuccess('修改成功！');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $permission = Permission::find($id);
        if (!$permission) {
            return redirect('/admin/menu')->withErrors("找不到该权限!");
        }
        if ($permission->delete()) {
            $permission->roles()->detach();
            $permission->users()->detach();
        } else {
            return redirect()->back()
                ->withErrors("删除失败");
        }

        //触发事件
        Event::fire(new permChangeEvent());
        //写一条记录
        event(new \App\Events\userActionEvent('\App\Models\Admin\Permission', $permission->id, 2, '删除了权限:' . $permission->name . '(' . $permission->label . ')'));

        return redirect()->back()
            ->withSuccess("删除成功");
    }
}
